package com.eascs.admin.sys.permission.controller;

import java.text.Format;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.sys.permission.form.RoleEmployeeForm;
import com.eascs.admin.sys.permission.form.SysRoleForm;
import com.eascs.app.dao.PageResult;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.sys.ActOrgRoleUserEntity;
import com.eascs.workflow.common.entity.sys.SysResources;
import com.eascs.workflow.common.entity.sys.SysResourcesFormEntity;
import com.eascs.workflow.common.entity.sys.SysRole;
import com.eascs.workflow.common.entity.sys.SysUser;
import com.eascs.workflow.common.entity.wf.DicData;
import com.eascs.workflow.common.service.sys.SysPermissionService;
import com.eascs.workflow.common.vo.ModelResult;

@Controller
@RequestMapping("/act/role")
public class RoleController extends PermissionBaseMasterViewController {
	@Reference
	private SysPermissionService sysPermissionService;

	@Value("${o2o.admin.ztree.diycss}")
	private String diycss;//图标样式
	
	final static int PAGE_SIZE = 15;

	@RequestMapping("/detail-{id}")
	public String detail(Model model, @PathVariable String id) {
		SysRole sysRole = new SysRole();
		User user = UserHolder.getUser();
		SysUser sysUser = new SysUser();
		sysUser.setEmployeeNo(Integer.valueOf(user.getNo()));
		if (id != null) {
			sysRole.setId(id);
			sysRole = sysPermissionService.selectRolesByRole(sysRole).getModel();
		}
		List<SysResources> myList = sysPermissionService.selectResourcesByRoles(sysRole).getModel();
		List<SysResources> allList = sysPermissionService.selectResourcesList().getModel();
		for(int i=0;i<allList.size();i++){
			SysResources item = allList.get(i);
			if(item.getResourceType()==StatusContexts.RESOURCE_TYPE_QX){
				item.setIconSkin(diycss);
			}
		}
		List<DicData> dicData = sysPermissionService.getDicDataByType("roleLevelType");
		model.addAttribute("dicData", dicData);
		model.addAttribute("allResList", JSON.toJSONString(allList));
		model.addAttribute("myResList", JSON.toJSONString(myList));
		model.addAttribute("role", sysRole);
		return "sys/roleInfo";
	}

	@SuppressWarnings("unused")
	@RequestMapping("/roleEmployee/add")
	public String addEmployee(Model model,RoleEmployeeForm form) {
		ActOrgRoleUserEntity orgRoleUserEntity = new ActOrgRoleUserEntity();
		try {
			BeanUtils.copyProperties(orgRoleUserEntity, form);
		} catch (Exception e) {}
		String url= "/act/role/roleEmployee/add";
		
		if (StringUtils.isNotBlank(form.getUserName()) || StringUtils.isNotBlank(form.getRoleId())) {
			String userName = form.getUserName() == null ? "" : form.getUserName();
			String roleId = form.getRoleId() == null ? "" : form.getRoleId();
			url = UrlUtil.appendUrl(url, "userName", userName);
			url = UrlUtil.appendUrl(url, "roleId", roleId);
			url = url + "&pageIndex=";
		} else {
			url = url + "&pageIndex=";
		}
		PageResult<Object[]> pageResult = null;
		if (null == form.getPageIndex()) {
			pageResult = new PageResult<>(10, 0, 0);
		} else {
			pageResult = sysPermissionService.selectOrgRoleUserPage(orgRoleUserEntity,form.getPageSize(),form.getPageIndex());
		}
		String[] titles = { "用户编号", "用户姓名", "组织", "角色" };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles,url);
		Button[] titleButton = new Button[] { new AjaxButton("删除", "/act/role/rest/userOrgRole/delete-")};
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setMoreButtons(titleButton);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("RoleEmployeeForm", form);
		//获取全部省区列表
		List<ActOrgEntity> orgList = sysPermissionService.getOrgListByLevel(null, ActOrgEntity.ORG_LEVEL_PROVINCE).getModel();
		//获取全部大区列表
		List<ActOrgEntity> areaList = sysPermissionService.getOrgListByLevel(null, ActOrgEntity.ORG_LEVEL_AREA).getModel();
		//角色类型列表
		List<SysRole> roleList = sysPermissionService.getRoleList().getModel();
		SysRole sysRole = sysPermissionService.getRoleById(form.getRoleId()).getModel();
		ViewContext.put("role", sysRole);
		ViewContext.put("orgList", orgList);
		ViewContext.put("areaList", areaList);
		return "sys/addRoleEmployee";
	}

	@RequestMapping("/addRoleRes")
	public String addRoleRes() {
		List<DicData> dicData = sysPermissionService.getDicDataByType("roleLevelType");
		ViewContext.put("dicData", dicData);
		return "sys/addRole";
	}

	@RequestMapping("/list")
	public String search(SysRoleForm sysRoleForm) {
		//用户为系统管理员，则可对所有角色作任何操作；如果非管理员有这个权限，则只能对角色分类为业务角色的角色进行操作
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "rolePermission");
		User user = UserHolder.getUser();
		boolean isSuperAdministrator = user.isSuperAdministrator();
		if (!isSuperAdministrator) {
			sysRoleForm.setRoleCategory("业务角色");
		}
		sysRoleForm.setPageSize(PAGE_SIZE);
		PageResult<Object[]> pageResult = null;
		if (null == sysRoleForm.getPageIndex()) {
			pageResult = new PageResult<>(10, 0, 0);
		} else {
			ModelResult<PageResult<Object[]>> modelResult = sysPermissionService
					.selectRolesPage(SysRoleConvert(sysRoleForm), PAGE_SIZE, sysRoleForm.getPageIndex());
			pageResult = modelResult.getModel();
		}
		String[] titles = { "角色编码", "角色名称", "角色描述" };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, "/act/role/list?pageIndex=");
		Button roleManageButt = ButtonHelper.createRedirectButton("编辑角色", "/act/role/detail-", "roleManage");
		Button roleAddtButton = ButtonHelper.createRedirectButton("添加人员", "/act/role/roleEmployee/add?roleId=", "roleAdd");
		Button roleDeleteButt = ButtonHelper.createAjaxButton("删除", "/act/role/rest/delete-", "roleDelete");		
		Button[] titleButton = new Button[] { roleManageButt, roleAddtButton, roleDeleteButt};
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setMoreButtons(titleButton);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("sysRoleForm", sysRoleForm);
		return "/sys/roleList";
	}

	private SysRole SysRoleConvert(SysRoleForm roleform) {
		User user = UserHolder.getUser();
		SysRole role = new SysRole();
		role.setId(roleform.getId());
		role.setRoleName(roleform.getRoleName());
		role.setRoleCode(roleform.getRoleCode());
		role.setDescription(roleform.getDescription());
		role.setUpdateTime(new Date());
		role.setCreateTime(new Date());
		role.setUpdator(user.getAccount());
		role.setCreator(user.getAccount());
		role.setRoleCategory(roleform.getRoleCategory());
		return role;
	}
	
	/**
	 * 分页查询-已分配角色清单
	 * @param entity
	 * @return
	 */
	@RequestMapping("/roleList")
	public String findRoleList(SysResourcesFormEntity entity) {
		String o2ourl = "/act/role/roleList";
		if (entity != null) {
			String id = entity.getId() == null ? "" : entity.getId();
			String roleName = entity.getRoleName() == null ? "" : entity.getRoleName();
			String roleCode = entity.getRoleCode() == null ? "" : entity.getRoleCode();
			o2ourl = UrlUtil.appendUrl(o2ourl, "id", id);
			o2ourl = UrlUtil.appendUrl(o2ourl, "roleName", roleName);
			o2ourl = UrlUtil.appendUrl(o2ourl, "roleCode", roleCode);
			o2ourl = o2ourl + "&pageIndex=";
		} else {
			o2ourl = o2ourl + "?pageIndex=";
		}
		entity.setPageSize(100);//分页大小为100
		PageResult<Object[]> pageResult = sysPermissionService.findRolePageByResId(entity);
		String[] titles = { "角色编号", "角色名称" };
		SelectDataOption[] selectDataOptions = { null, null };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, o2ourl);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[] { null, null });
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", entity);
		return "sys/listRole";
	}
	
	/**
	 * 分页查询-已分配人员清单
	 * @param entity
	 * @return
	 */
	@RequestMapping("/employeeList")
	public String findEmployeeList(SysResourcesFormEntity entity) {
		String o2ourl = "/act/role/employeeList";
		if (entity != null) {
			String id = entity.getId() == null ? "" : entity.getId();
			String orgName = entity.getOrgName() == null ? "" : entity.getOrgName();
			String employeeCode = entity.getEmployeeCode() == null ? "" : entity.getEmployeeCode();
			String employeeNamecn = entity.getEmployeeNamecn() == null ? "" : entity.getEmployeeNamecn();
			o2ourl = UrlUtil.appendUrl(o2ourl, "id", id);
			o2ourl = UrlUtil.appendUrl(o2ourl, "orgName", orgName);
			o2ourl = UrlUtil.appendUrl(o2ourl, "employeeCode", employeeCode);
			o2ourl = UrlUtil.appendUrl(o2ourl, "employeeNamecn", employeeNamecn);
			o2ourl = o2ourl + "&pageIndex=";
		} else {
			o2ourl = o2ourl + "?pageIndex=";
		}
		entity.setPageSize(100);//分页大小为100
		PageResult<Object[]> pageResult = sysPermissionService.findEmployeePageByResId(entity);
		String[] titles = { "机构","人员工号", "人员姓名" };
		SelectDataOption[] selectDataOptions = { null, null, null };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, o2ourl);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[] { null, null, null });
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", entity);
		return "sys/listEmployee";
	}
	
	
	/**
	 * 根据人找权限(人员自动过滤控件、权限树展示该人员的权限信息)
	 * @param entity
	 * @return
	 */
	@RequestMapping("/resourcesList")
	public String findResourcesList(Model model,SysUser user) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "RYQXCK");
		String o2ourl = "/act/role/resourcesList";
		if (user != null) {
			String employeeNo = user.getEmployeeNo() == null ? "" : user.getEmployeeNo()+"";
			o2ourl = UrlUtil.appendUrl(o2ourl, "employeeNo", employeeNo);
			o2ourl = o2ourl + "&pageIndex=";
		} else {
			o2ourl = o2ourl + "?pageIndex=";
		}		
		List<SysResources> myList = sysPermissionService.queryResourcesByUser(user).getModel();
		List<SysResources> allList = sysPermissionService.selectResourcesList().getModel();
		List<DicData> dicData = sysPermissionService.getDicDataByType("roleLevelType");
		User vo = sysPermissionService.getSysUserById(user.getEmployeeNo()+"").getModel();//根据人员ID查人员信息
		model.addAttribute("dicData", dicData);
		model.addAttribute("allResList", JSON.toJSONString(allList));
		model.addAttribute("myResList", JSON.toJSONString(myList));
		model.addAttribute("user", user);
		model.addAttribute("vo", vo);
		return "sys/listResource";
	}
	
	
}
